<template>
  <div>
    <div class="table_ground">
      <div class="module_name">班级管理</div>
      <div class="input_button">
        <div class="input_box">
          <el-input placeholder="请输入用户名查询" size="small"  v-model="search.gradeName" class="input_left">
            <template #suffix>
              <el-icon class="el-input__icon"><search /></el-icon>
            </template>
          </el-input>
          <el-button type="success" size="small" style="border-radius: 1px;width: 100px;text-align: center" @click="load">查询</el-button>
        </div>

        <div class="button_box">
          <el-button type="success" size="small" style="border-radius: 1px;width: 100px;text-align: center" @click="add" v-if="user.role === 1">新增</el-button>
        </div>
      </div>
      <el-table
          :data="tableData"
          border
          :fit="true"
          stripe
          style="width: 100%"
          :cell-style="{ textAlign: 'center' }"
          :header-cell-style="{ textAlign: 'center' }"
      >

        <el-table-column prop="gradeName" label="班级名"></el-table-column>
        <el-table-column prop="brief" label="简介"></el-table-column>
        <el-table-column fixed="right" label="操作" v-if="user.role === 1">
          <template #default="{ row }">
<!--            <el-button @click="handleClick(row)" type="text" size="small">查看</el-button>-->
            <el-button type="text" size="small" @click="edit(row)">编辑</el-button>
            <!--            <el-button type="text" size="small" @click="edit('123')">编辑2</el-button>-->
            <!--            <el-button type="text" size="small">编辑</el-button>-->
            <el-popconfirm title="确定删除吗？"  @confirm="del(row.id)">
              <template #reference>
                <el-button type="text" size="small">删除</el-button>
              </template>
            </el-popconfirm>

          </template>
        </el-table-column>
      </el-table>

      <div class="block" style="text-align: right; margin-top: 20px">
        <!--        <el-pagination-->
        <!--            v-model:current-page="pageNum"-->
        <!--            :page-size="5"-->
        <!--            :size="size"-->
        <!--            :disabled="disabled"-->
        <!--            :background="background"-->
        <!--            layout="total, prev, pager, next"-->
        <!--            :total="1000"-->
        <!--            @size-change="handleSizeChange"-->
        <!--            @current-change="handleCurrentChange"-->
        <!--        />-->

        <el-pagination
            background
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            :page-size="5"
            layout="total, prev, pager, next"
            :total="total"
        />
      </div>
    </div>

    <!--    <div class="block" style="text-align: right; margin-top: 20px">-->

    <!--    </div>-->

    <!--    <template v-slot="scope">-->
    <!--      <el-image :src="scope.row.avatar" :preview-src-list="[scope.row.avatar]" style="width: 50px; height: 50px; border-radius: 50%"></el-image>-->
    <!--    </template>-->


    <el-dialog title="请填写信息" v-model="dialogVisible" width="40%">
      <el-form :model="form" label-position="right" label-width="100px" style="padding-right: 40px">
        <el-form-item label="班级名">
          <el-input size="small" v-model="form.gradeName" placeholder="请输入班级名"></el-input>
        </el-form-item>
        <el-form-item label="简介">
          <el-input size="small" v-model="form.brief" placeholder="请输入班级简介"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogVisible = false">取 消</el-button>
        <el-button size="small" type="primary" @click="save">保 存</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<!--<script setup>-->
<script lang="ts" setup>
import { ref } from 'vue'
// import { ref, reactive } from 'vue';
import type { ComponentSize } from 'element-plus'
import {Plus, Search} from "@element-plus/icons-vue";
import request from '@/utils/request';
import {ElNotification} from "element-plus";
import { onMounted } from 'vue';
import { ElMessage } from 'element-plus'
import type { UploadProps } from 'element-plus'
// import {reactive} from "vue/dist/vue";
import {reactive} from "vue";

const form = ref<{ [key: string]: any }>({
});

const user = reactive(JSON.parse(localStorage.getItem('user') || '{}'));

const dialogVisible = ref(false);  // 控制弹框的显示状态

const input = ref<string>('');
const pageNum = ref<number>(1);
let total = ref<number>(0);
const search = ref<{ [key: string]: any }>({});
let tableData = ref<any[]>([]);

const gradeData = ref<{ [key: string]: any }>({});

// const gradeData = ref<any[]>([]);

const dialogRole = ref<boolean>(false);

onMounted(() => {
  load();
  loadGrade();
});

const load = () => {

  console.log('搜索结果', search.value.gradeName);

  //Get 方法获取所有数据
  // request.get("grade/alldata").then((res: any) => {
  //
  //   if (res.code === '0') {
  //     // @ts-ignore
  //      tableData.value = res.data;
  //     // this.tableData = res.data
  //   } else {
  //     // @ts-ignore
  //     // this.$notify.error(res.msg);
  //
  //     ElNotification.error({
  //       title: '错误啦，请在 IDEA 搜索：error_01 ',
  //       message: res.msg
  //     });
  //   }
  // });

  request.post("/grade/page?pageNum=" + pageNum.value, search.value).then((res: any) => {

    if (res.code === '0') {
      tableData.value = res.data.list;
      total.value = res.data.total;
      // tableData.value[0].id = '777'
    } else {
      // this.$notify.error(res.msg);
      ElNotification.error({
        title: '错误啦，请在 IDEA 搜索：grade_error_01 ',
        message: res.msg
      });
    }

    console.log('load() --- ', res);
  });

};

const add = (): void => {
  form.value = {
    role: 1//默认管理员
  };
  dialogVisible.value = true;
};

// @ts-ignore
const del = async (id: number): Promise<void> => {
  //方法一
  // try {
  //   const res: any = await request.delete(`/grade/${id}`);
  //   if (res.code === '0') {
  //     ElNotification.success('删除成功');
  //     load();
  //   } else {
  //     ElNotification.error(res.msg);
  //   }
  // } catch (error) {
  //   ElNotification.error('删除失败，请重试');
  // }

  //方法二
  request.delete("/grade/" + id).then((res: any) => {
    if (res.code === '0') {
      ElNotification.success('删除成功');
      load();
    } else {
      ElNotification.error(res.msg);
    }
  });
};

const edit = (row: { [key: string]: any }) => {
  dialogVisible.value = true;
  form.value = row;
  console.log('row 是否有值:', row);  // 如果没有值，检查数据渲染问题
};

// @ts-ignore
const save = async (): Promise<void> => {

  if (!form.value.id){ //如果没有id 走新增接口
    request.post("/grade",form.value).then((res: any) =>{ //post请求把form对象传到后端，后端写逻辑把form存到数据库里

      if (res.code === '0'){ //如果接口调用成功，则把模态框关闭，重新加载一下数据库的数据

        ElNotification.success('新增成功');
        dialogVisible.value = false;
        load();
      } else {
        ElNotification.error(res.msg);// 如果不成功，返回报错信息
      }
    })
    console.log('--- 新增');
  }
  else {
    request.post("/grade/edit",form.value).then((res: any) =>{ //post请求把form对象传到后端，后端写逻辑把form存到数据库里

      if (res.code === '0'){
        ElNotification.success('修改成功');
        dialogVisible.value = false;
        load();
      } else {
        ElNotification.error(res.msg);
      }
    })
    console.log('--- 修改');
  }
};

const currentPage1 = ref(5)
const size = ref<ComponentSize>('default')
const background = ref(true)
const disabled = ref(false)

const handleClick = (row: { [key: string]: any }) => {
  console.log(row)
}
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
}
// const handleCurrentChange = (val: number) => {
//   console.log(`current page: ${val}`)
// }
// 处理分页变化
const handleCurrentChange = (newPage: number) => {
  pageNum.value = newPage;
  console.log('当前页码:', newPage);
  load(); // 重新加载数据
};

const loadGrade = () => {

  request.get('/grade/alldata').then((res: any) => {

    if (res.code === '0') {
      gradeData.value = res.data;
      // console.log('gradeData.value --- ', gradeData.value);
      // console.log(gradeData.value[0].id);
      // console.log(gradeData.value[0].gradeName);

      tableData.value[0].id = '888'

      for (const key in gradeData.value) {

        console.log(`---a`, key)

        const value = gradeData.value[key]

        console.log(`---id`, value.id)
        console.log(`---gradeName`, value.gradeName)

        console.log(`---b ${key}: ${value}`)
      }

    } else {
      // this.$notify.error(res.msg);
      ElNotification.error({
        title: '错误啦，请在 IDEA 搜索：grade_error_01 ',
        message: res.msg
      });
    }

    console.log('loadGrade() --- ', res);
  });

};

const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
  form.value.avatar = response.data;
  // form.value.imageUrl = URL.createObjectURL(uploadFile.raw!)
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {

  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}

</script>
